import  UIKit
import Kingfisher
import  GrowingTextView
import Alamofire
import Toast_Swift
import GradientLoadingBar

class CompletionImageViewController: UIViewController,GrowingTextViewDelegate{
    var type: Int = 0
    var rolePrompt = ""
    var pageTitle = "AI绘图"
    var resultType = 1
    let scrollView = UIScrollView()
    var growingTextView: GrowingTextView!
    var clearButton: UIButton!
    var size = "256x256"
    var shortButton: UIButton!
    var middleButton: UIButton!
    var longButton: UIButton!
    var copyButton: UIButton!
    var completionButton: UIButton!
    var resultTitleLabel: UILabel!
    var resultLabel: UILabel!
    var tipsLabel: UILabel!
    var containerView: UIView!
    var imageView: UIImageView!
    var imageData: UIImage?
    let notchGradientLoadingBar = NotchGradientLoadingBar(
        height: 3.0
    )
    override func viewDidLoad() {
        navigationItem.title = pageTitle
        view.backgroundColor = .white
        view.addSubview(scrollView)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom).offset(-56)
        }
        containerView = UIView()
        scrollView.addSubview(containerView)
        containerView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            make.width.equalTo(UIScreen.main.bounds.width)
        }
        
        let titelLabel = UILabel()
        titelLabel.font = UIFont.boldSystemFont(ofSize: 15)
        titelLabel.textColor = .darkText
        titelLabel.text = "图片描述"
        containerView.addSubview(titelLabel)
        titelLabel.snp.makeConstraints({ make in
            make.top.equalTo(containerView.safeAreaLayoutGuide.snp.top).offset(12)
            make.left.equalTo(containerView).offset(16)
        })
        
        growingTextView = GrowingTextView()
        growingTextView.minHeight = UIScreen.main.bounds.height/5
        growingTextView.maxHeight = UIScreen.main.bounds.height/4
        growingTextView.tintColor = .darkText
        growingTextView.backgroundColor = commonLightBackgroundColor
        growingTextView.placeholder = "请详细描述您想要创作的图片，越详细越好"
        growingTextView.layer.cornerRadius = 12
        growingTextView.font = UIFont.systemFont(ofSize: 15)
        growingTextView.delegate = self
        containerView.addSubview(growingTextView)
        growingTextView.snp.makeConstraints({ make in
            make.top.equalTo(titelLabel.snp.bottom).offset(12)
            make.left.equalTo(containerView).offset(16)
            make.right.equalTo(containerView).offset(-16)
            make.width.equalTo(UIScreen.main.bounds.width-32)
        })
        
        
        clearButton = UIButton(type: .custom)
        clearButton.setTitle((growingTextView.text == nil || growingTextView.text == "") ? "粘贴" :  "清空", for: .normal)
        clearButton.setTitleColor(.primaryColor, for: .normal)
        clearButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .semibold)
        
        clearButton.isUserInteractionEnabled = true
        clearButton.addTarget(self, action: #selector(handleClearButtonTapped(_:)), for: .touchUpInside)
        containerView.addSubview(clearButton)
        clearButton.snp.makeConstraints({ make in
            make.bottom.equalTo(growingTextView.snp.bottom)
            make.right.equalTo(growingTextView)
            make.width.equalTo(62)
            make.height.equalTo(32)
        })
        
        
        let lengthLabel = UILabel()
        lengthLabel.font = UIFont.boldSystemFont(ofSize: 15)
        lengthLabel.textColor = .darkText
        lengthLabel.text = "图片尺寸 "
        containerView.addSubview(lengthLabel)
        lengthLabel.snp.makeConstraints({ make in
            make.top.equalTo(growingTextView.snp.bottom).offset(24)
            make.left.equalTo(titelLabel)
        })
        
        
        
        shortButton = UIButton(type: .custom)
        shortButton.setTitle("256x256", for: .normal)
        shortButton.layer.cornerRadius = 12
        shortButton.setTitleColor(.primaryColor, for: .normal)
        shortButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .semibold)
        shortButton.layer.borderColor = (UIColor.primaryColor).cgColor
        shortButton.layer.borderWidth = 1
        shortButton.isUserInteractionEnabled = true
        shortButton.addTarget(self, action: #selector(handleShortButtonTapped(_:)), for: .touchUpInside)
        containerView.addSubview(shortButton)
        shortButton.snp.makeConstraints({ make in
            make.top.equalTo(lengthLabel.snp.bottom).offset(16)
            make.left.equalTo(titelLabel)
            make.width.equalTo(82)
            make.height.equalTo(32)
        })
        
        
        middleButton = UIButton(type: .custom)
        middleButton.setTitle("512x512", for: .normal)
        middleButton.layer.cornerRadius = 12
        middleButton.setTitleColor(.darkText, for: .normal)
        middleButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .semibold)
        middleButton.layer.borderColor = (UIColor.gray).cgColor
        middleButton.layer.borderWidth = 1
        middleButton.isUserInteractionEnabled = true
        middleButton.addTarget(self, action: #selector(handleMiddleButtonTapped(_:)), for: .touchUpInside)
        containerView.addSubview(middleButton)
        middleButton.snp.makeConstraints({ make in
            make.top.equalTo(shortButton)
            make.left.equalTo(shortButton.snp.right).offset(16)
            make.width.equalTo(82)
            make.height.equalTo(32)
        })
        
        
        longButton = UIButton(type: .custom)
        longButton.setTitle("1024x1024", for: .normal)
        longButton.layer.cornerRadius = 12
        longButton.setTitleColor(.darkText, for: .normal)
        longButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .semibold)
        longButton.layer.borderColor = (UIColor.gray).cgColor
        longButton.layer.borderWidth = 1
        longButton.isUserInteractionEnabled = true
        longButton.addTarget(self, action: #selector(handleLongButtonTapped(_:)), for: .touchUpInside)
        containerView.addSubview(longButton)
        longButton.snp.makeConstraints({ make in
            make.top.equalTo(shortButton)
            make.left.equalTo(middleButton.snp.right).offset(16)
            make.width.equalTo(82)
            make.height.equalTo(32)
        })
        
        
        resultTitleLabel = UILabel()
        resultTitleLabel.isHidden = true
        resultTitleLabel.font = UIFont.boldSystemFont(ofSize: 15)
        resultTitleLabel.textColor = .darkText
        resultTitleLabel.text = "生成结果"
        containerView.addSubview(resultTitleLabel)
        resultTitleLabel.snp.makeConstraints({ make in
            make.top.equalTo(shortButton.snp.bottom).offset(32)
            make.left.equalTo(titelLabel)
        })
        
        
        copyButton = UIButton(type: .custom)
        copyButton.isHidden = true
        copyButton.setTitle("保存", for: .normal)
        copyButton.layer.cornerRadius = 12
        copyButton.setTitleColor(.primaryColor, for: .normal)
        copyButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .semibold)
        copyButton.layer.borderColor = (UIColor.primaryColor).cgColor
        copyButton.layer.borderWidth = 1
        copyButton.isUserInteractionEnabled = true
        copyButton.addTarget(self, action: #selector(handleSavedButtonTapped(_:)), for: .touchUpInside)
        containerView.addSubview(copyButton)
        copyButton.snp.makeConstraints({ make in
            make.top.equalTo(resultTitleLabel)
            make.right.equalTo(containerView).offset(-16)
            make.width.equalTo(52)
            make.height.equalTo(28)
        })
        
        
        
        
        
        imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit

        containerView.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.top.equalTo(copyButton.snp.bottom).offset(12)
            make.width.height.equalTo(UIScreen.main.bounds.width)
        }
        
        
        containerView.snp.makeConstraints({ (make) in
            make.bottom.equalTo(imageView.snp.bottom)
            
        })
        
        
        self.view.isUserInteractionEnabled = true
        self.view.addGestureRecognizer(UITapGestureRecognizer(target:self, action:#selector(self.handleTap(_:))))
        
        
        
        completionButton = UIButton(type: .custom)
        completionButton.setTitle("开始绘图", for: .normal)
        completionButton.setTitle("绘图中...", for: .selected)
        completionButton.setTitleColor(.white, for: .normal)
        completionButton.setTitleColor(.darkGray, for: .selected)
        completionButton.layer.cornerRadius = 21
        completionButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
        completionButton.frame.size = CGSize(width: 68, height: 20)
        completionButton.backgroundColor = .primaryColor
        completionButton.addTarget(self, action: #selector(handleCompletionButtonTapped(_:)), for: .touchUpInside)
        self.view.addSubview(completionButton)
        completionButton.snp.makeConstraints { make in
            make.centerX.equalTo(self.view)
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.bottom).offset(-42)
            make.height.equalTo(42)
            make.width.equalTo(UIScreen.main.bounds.width*2/3)
            
        }
        
        
        tipsLabel = UILabel()
        tipsLabel.font = UIFont.boldSystemFont(ofSize: 11)
        tipsLabel.textColor = .gray
        tipsLabel.text = "AI绘图相对于聊天会花费更多的时间，请一定耐心等待"
        containerView.addSubview(tipsLabel)
        tipsLabel.snp.makeConstraints({ make in
            make.bottom.equalTo(completionButton.snp.top).offset(-12)
            make.centerX.equalTo(completionButton)
        })
        
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.6){
            self.growingTextView.becomeFirstResponder()
        }
        
        
        let toolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0,  width: self.view.frame.size.width, height: 30))
                let flexSpace = UIBarButtonItem(barButtonSystemItem:    .flexibleSpace, target: nil, action: nil)
                let doneBtn: UIBarButtonItem = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(dismissMyKeyboard))
                toolbar.setItems([flexSpace, doneBtn], animated: false)
                toolbar.sizeToFit()
                growingTextView.inputAccessoryView = toolbar
    }
    
    @objc func dismissMyKeyboard() {
           view.endEditing(true)
       }
    @objc private func handleClearButtonTapped(_ sender: Any) {
        if let text = growingTextView.text {
            if text == "" {
                let pasteboard = UIPasteboard.general
                if let pasteboardString = pasteboard.string {
                    growingTextView.text = pasteboardString
                    print("粘贴板的内容是：\(pasteboardString)")
                } else {
                    self.view.makeToast("粘贴板没有可用的字符串内容",position: .center)
                   
                    print("粘贴板没有可用的字符串内容")
                }
            }else{
                growingTextView.text = ""
            }
            clearButton.setTitle((growingTextView.text == nil || growingTextView.text == "") ? "粘贴" :  "清空", for: .normal)
        }
        
    }
    
    @objc private func handleCompletionButtonTapped(_ sender: Any) {
       
        if let prompt = growingTextView.text, prompt != ""{
            print("prompt\(prompt)")
            print("handleCompletionButtonTapped")
            completionButton.isUserInteractionEnabled = false
            completionButton.isSelected =  true
            completionButton.backgroundColor = .lightGray
            notchGradientLoadingBar.fadeIn()
            
            
            let url = "chatgpt/imageCreator"
            let parameters = CompletionImageParameters(size: size, prompt: prompt)
            
            AFManager.sharedInstance.manager.request("\(baseUrl)\(url)",method: .post,parameters: parameters,encoder: URLEncodedFormParameterEncoder.default).responseString { response in
                self.completionButton.isUserInteractionEnabled = true
                self.notchGradientLoadingBar.fadeOut()
                self.completionButton.isSelected =  false
                self.completionButton.backgroundColor = .primaryColor
                if let string = response.value{
                    print(string)
                    let data = Data(string.utf8)
                    do {
                        let jsonDecoder = JSONDecoder()
                        let baseResponse = try jsonDecoder.decode(BaseResponse.self, from: data)
                        let resultString = baseResponse.message
                        
                        let url = URL(string: resultString)
                        let processor = DownsamplingImageProcessor(size: self.imageView.bounds.size)
                        |> RoundCornerImageProcessor(cornerRadius: 0)
                        self.imageView.kf.indicatorType = .activity
                        self.imageView.kf.setImage(
                            with: url,
                            placeholder: UIImage(named: "placeholderImage"),
                            options: [
                                .processor(processor),
                                .scaleFactor(UIScreen.main.scale),
                                .transition(.fade(1)),
                                .cacheOriginalImage
                            ])
                        {
                            result in
                            switch result {
                            case .success(let value):
                                self.imageData =  value.image
                                self.notchGradientLoadingBar.fadeOut()
                                self.completionButton.isSelected =  false
                                self.completionButton.backgroundColor = .primaryColor
                                self.resultTitleLabel.isHidden = false
                                self.copyButton.isHidden = false
                            case .failure(let error):
                                print("Job failed: \(error.localizedDescription)")
                            }
                        }
                        
                        
                        
                        if resultString.contains(haveNoTryCount) || resultString.contains(isNotVip){
                            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1){
                                
                                let detailViewController = VipViewController()
                                detailViewController.fromPage = "AI绘画-\(prompt)"
                                self.navigationController?.pushViewController(detailViewController, animated: true)
                            }
                        }
                    } catch {
                        print(error)
                    }
                }else{
                    
                }
            }
        }else{
            self.view.makeToast("请填写描述",position: .center)
        }
        
        
        
        
    }
    
    @objc private func handleShortButtonTapped(_ sender: Any) {
        shortButton.layer.borderColor = (UIColor.primaryColor).cgColor
        middleButton.layer.borderColor = (UIColor.gray).cgColor
        longButton.layer.borderColor = (UIColor.gray).cgColor
        shortButton.setTitleColor(.primaryColor, for: .normal)
        middleButton.setTitleColor(.darkText, for: .normal)
        longButton.setTitleColor(.darkText, for: .normal)
        resultType = 1
        size = "256x256"
        
    }
    
    @objc private func handleMiddleButtonTapped(_ sender: Any) {
        shortButton.layer.borderColor = (UIColor.gray).cgColor
        middleButton.layer.borderColor = (UIColor.primaryColor).cgColor
        longButton.layer.borderColor = (UIColor.gray).cgColor
        
        shortButton.setTitleColor(.darkText, for: .normal)
        middleButton.setTitleColor(.primaryColor, for: .normal)
        longButton.setTitleColor(.darkText, for: .normal)
        resultType = 2
        size = "512x512"
        
    }
    
    @objc private func handleLongButtonTapped(_ sender: Any) {
        shortButton.layer.borderColor = (UIColor.gray).cgColor
        middleButton.layer.borderColor = (UIColor.gray).cgColor
        longButton.layer.borderColor = (UIColor.primaryColor).cgColor
        
        shortButton.setTitleColor(.darkText, for: .normal)
        middleButton.setTitleColor(.darkText, for: .normal)
        longButton.setTitleColor(.primaryColor, for: .normal)
        resultType = 3
        self.view.makeToast("生成高清图片需要花费更多的时间，请耐心等待。",position: .center)
        size = "1024x1024"
        
    }
    
    @objc private func handleSavedButtonTapped(_ sender: Any) {
        self.view.makeToast("保存成功",position: .center)
        print("copy")
        
        let imageSaver = ImageSaver()
        if let uiImage = imageData {
            imageSaver.writeToPhotoAlbum(image: uiImage)
        }
        
        
    }
    
    @objc private func handleTap(_ sender: Any) {
        self.view.endEditing(true)
        print("handleTap")
        
    }
    override var wx_titleTextAttributes: [NSAttributedString.Key : Any]? {
        return [NSAttributedString.Key.foregroundColor: UIColor.white]
    }
    
    override var wx_navigationBarBackgroundColor: UIColor? {
        return commonDarkBackgroundColor
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
        print("touch began")
    }
    
    
    func textViewDidEndEditing(_ textView: UITextView) {
    }
}

class ImageSaver: NSObject {
    func writeToPhotoAlbum(image: UIImage) {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveError), nil)
    }
    
    @objc func saveError(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        print("save finished")
    }
}
